package main;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;

/**
 * Stores a list of Contacts. Gives sorting functionality, and
 * search functionality.
 *
 *@author Meng
 *
 */
public class ContactList implements Serializable {

	private ArrayList<Contact> contacts;
    
    public ContactList() {
    	contacts = new ArrayList<Contact>();
    }
    
    /**
     * Add a new contact with the given information
     * @param newContact
     */
    public void addContact(Contact newContact) {
        contacts.add(newContact);
        Disk.write(this);
    }
    
    /**
     * Sorts the contacts by last name
     */
    public void sort() {
    	Collections.sort(contacts);
    }
    
    /**
     * 
     * @param zipCode
     * @return list of contacts given the zip code
     */
    public String searchByZip(String zipCode) {
        ContactList resultList = new ContactList();
        for (int i = 0; i < contacts.size(); i++) {
        	if (zipCode.equals(contacts.get(i).getZipCode())) {
        	    resultList.addContact(contacts.get(i));
        	}		
        }
        String results = resultList.toString();
        if(results.equals("")) {
            results = "No Results";
        }
        return results;
    }
    
    /**
     * 
     * @param lastName
     * @return list of contacts given the last Name
     */
    public String searchByLastName(String lastName) {
        ContactList resultList = new ContactList();
        for (int i = 0; i < contacts.size(); i++) {
        	if (lastName.equalsIgnoreCase(contacts.get(i).getLastName())) {
        	    resultList.addContact(contacts.get(i));
        	}		
        }
        String results = resultList.toString();
        if(results.equals("")) {
            results = "No Results";
        }
        return results;
    }
    
    /**
     * 
     * @param email
     * @return list of contacts given the email
     */
    public String searchByEmail(String email) {
    	ContactList resultList = new ContactList();
        for (int i = 0; i < contacts.size(); i++) {
        	if (email.equalsIgnoreCase(contacts.get(i).getEmailAddress())) {
        		resultList.addContact(contacts.get(i));
        	}		
        }
        String results = resultList.toString();
        if(results.equals("")) {
            results = "No Results";
        }
        return results;
    }
    
    /**
     * @return a string containing all of the contacts
     */
    public String toString() {
    	String list = "";
    	for(int i = 0; i < contacts.size(); i++) {
    		list = list + contacts.get(i).toString() + "\n" + "\n";
    	}
        return list;
    }
}